package org.hhqk.common;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Date Utility Class
 * This is used to convert Strings to Dates and Timestamps
 * <p/>
 * <p>
 * <a href="DateUtil.java.html"><i>View Source</i></a>
 * </p>
 *
 * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
 *         Modified by <a href="mailto:dan@getrolling.com">Dan Kibler </a>
 *         to correct time pattern. Minutes should be mm not MM
 *         (MM is month).
 * @version $Revision: 1.7.2.1 $ $Date: 2006-10-03 12:58:45 -0600 (Tue, 03 Oct 2006) $
 */
public class DateUtil {
    //~ Static fields/initializers =============================================

//	private static final Logger log = LoggerFactory.getLogger(DateUtil.class);
    public static String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";
    public static String DEFAULT_DATE_TIME_PATTERN = DEFAULT_DATE_PATTERN + " HH:mm:ss";
    private static String timePattern = "HH:mm";

    //~ Methods ================================================================

    /**
     * Return default datePattern (yyyy/MM/dd)
     *
     * @return a string representing the date pattern on the UI
     */
    public static String getDatePattern() {
        return DEFAULT_DATE_PATTERN;
    }
    
    public static String getDateTimePattern() {
        return DateUtil.getDatePattern() + " HH:mm:ss.S";
    }

    /**
     * This method attempts to convert an Oracle-formatted date
     * in the form dd-MMM-yyyy to mm/dd/yyyy.
     *
     * @param aDate date from database as a string
     * @return formatted string for the ui
     */
    public static final String getDate(Date aDate) {
        SimpleDateFormat df = null;
        String returnValue = "";

        if (aDate != null) {
            df = new SimpleDateFormat(getDatePattern());
            returnValue = df.format(aDate);
        }

        return (returnValue);
    }

    public static final Date getTimePart(Date datetime) {
        return convertStringToDate(formatDateToString(datetime, "HH:mm:ss"), "HH:mm:ss");
    }

    /**
     * This method generates a string representation of a date/time
     * in the format you specify on input
     *
     * @param strDate a string representation of a date
     * @param mask   the date pattern the string is in
     * @return a converted Date object
     * @throws ParseException
     * @see java.text.SimpleDateFormat
     */
    public static final Date convertStringToDate(String strDate, String mask) {
        SimpleDateFormat df = null;
        Date date = null;
        df = new SimpleDateFormat(mask);

//        if (log.isDebugEnabled()) {
//            log.debug("converting '" + strDate + "' to date with mask '"
//                    + mask + "'");
//        }

        try {
            date = df.parse(strDate);
        } catch (ParseException pe) {
//            log.error("ParseException: " + pe);
            //throw new ParseException(pe.getMessage(), pe.getErrorOffset());
        }

        return (date);
    }

    /**
     * This method returns the current date time in the format:
     * yyyy-MM-dd HH:MM a
     *
     * @param theTime the current time
     * @return the current date/time
     */
    public static String getTimeNow(Date theTime) {
        return formatDateToString(theTime, timePattern);
    }

    /**
     * This method converts a String to a date using the datePattern
     *
     * @param strDate the date to convert (in format yyyy-MM-dd)
     * @return a date object
     * @throws ParseException
     */
    public static Date convertStringToDate(String strDate) {
        Date aDate = null;

//        if (log.isDebugEnabled()) {
//            log.debug("converting date with pattern: " + getDatePattern());
//        }

        aDate = convertStringToDate(strDate, getDatePattern());
        return aDate;
    }

    /**
     * This method converts a String to a date using the datePattern
     *
     * @param strDate the date to convert (in format yyyy-MM-dd HH:mm:ss)
     * @return a date object
     * @throws ParseException
     */
    public static Date convertStringToDateTime(String strDate) {
        Date aDate = null;

//        if (log.isDebugEnabled()) {
//            log.debug("converting date with pattern: " + getDatePattern());
//        }

        aDate = convertStringToDate(strDate, getDateTimePattern());
        return aDate;
    }

    public static String formatDateToString(Date date, String pattern) {
        SimpleDateFormat f = new SimpleDateFormat(pattern);
        return f.format(date);
    }

    public static String formatDateToString(Date date) {
        SimpleDateFormat f = new SimpleDateFormat(getDatePattern());
        return f.format(date);
    }
    
    public static String formatDateTimeToString(Date date) {
        SimpleDateFormat f = new SimpleDateFormat(getDateTimePattern());
        return f.format(date);
    }

    @Deprecated
    public static Date getFirstDateOnMonth() {
        Date date = new Date();
        date.setDate(1);
        return date;
    }

    public static int geYears(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal.get(Calendar.YEAR);
    }

    public static int getMonths(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal.get(Calendar.MONTH);
    }

    public static int getDays(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * Field number for get and set indicating the hour of the day. HOUR_OF_DAY is used for the 24-hour clock.
     * E.g., at 10:04:15.250 PM the HOUR_OF_DAY is 22.
     * @param date
     * @return
     */
    public static int getHours(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal.get(Calendar.HOUR_OF_DAY);
    }

    public static int getMinutes(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal.get(Calendar.MINUTE);
    }

    public static int getSeconds(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal.get(Calendar.SECOND);
    }
    /**
     * 获取月的最后一天
     * @param month
     * 偏移量
     * @return
     */
    public static Date getFirstDayOfMonth(int month) {
        Calendar cal = Calendar.getInstance();

        //cal.setTime(this.fiducialDate);
        cal.set(Calendar.MONTH, month);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.set(Calendar.HOUR, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

    /**
     * 获取月的最后一天
     * @param month
     * 偏移量
     * @return
     */
    public static Date getLastDayOfMonth(int month) {
        Calendar cal = Calendar.getInstance();
        //cal.setTime(this.fiducialDate);
        cal.set(Calendar.MONTH, month + 1);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.add(Calendar.DAY_OF_MONTH, -1);
        cal.set(Calendar.HOUR, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }


    public static Date getFirstDayOfMonth(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.set(Calendar.HOUR, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

    public static Date getLastDayOfMonth(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int month = cal.get(Calendar.MONTH);
        cal.add(Calendar.MONTH, month + 1);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.add(Calendar.DAY_OF_MONTH, -1);

        cal.set(Calendar.HOUR, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);

        return cal.getTime();
    }

    public static Date getCurrentDate() {
        return new Date(System.currentTimeMillis());
    }

    public static Date getTomorrow() {
        Date todayDate = new Date(System.currentTimeMillis());
    	return new Date(getDay(todayDate).getTime() + 24*60*60*1000);
    }

    public static Date getTomorrowOfDay(Date day) {
    	return new Date(day.getTime() + 24*60*60*1000);
    }

    public static Date getDay(Date datetime) {
        return DateUtil.convertStringToDate(DateUtil.formatDateToString(datetime));
    }

    public static long getNumberOfDays(Date startDay, Date endDay) {
        return (endDay.getTime() - startDay.getTime()) / (24 * 3600 * 1000);
    }

    public static Date assembleDate(Date day, Date time) {
        return DateUtil.convertStringToDate(DateUtil.formatDateToString(day, "yyyy-MM-dd ") + DateUtil.formatDateToString(time, "HH:mm:ss"), "yyyy-MM-dd HH:mm:ss");
    }
    
    public static boolean validate(String dateString) {   
        //使用正则表达式 测试 字符 符合 dddd-dd-dd 的格式(d表示数字)       
        Pattern p = Pattern.compile("\\d{4}\\d{1,2}\\d{1,2}");
        Matcher m = p.matcher(dateString);   
        if (!m.matches()) {   
            return false;   
        } //得到年月日          
        int year = Integer.valueOf(dateString.substring(0, 4));
        int month = Integer.valueOf(dateString.substring(4, 6));
        int day = Integer.valueOf(dateString.substring(6, 8));
        if (month < 1 || month > 12) {
            return false;   
        }   
        int[] monthLengths = new int[] { 0, 31, -1, 31, 30, 31, 30, 31, 31, 30,   
                31, 30, 31 };   
        if (isLeapYear(year)) {   
            monthLengths[2] = 29;   
        } else {   
            monthLengths[2] = 28;   
        }   
        int monthLength = monthLengths[month];   
        if (day < 1 || day > monthLength) {   
            return false;   
        }   
        return true;   
    }   

    public static boolean validate(String dateString,String format) {   
        //使用正则表达式 测试 字符 符合 dddd+分隔符+dd+分隔符+dd 的格式(d表示数字),分隔符可没有
        String separator = null;
        if (format.length() > 8){//有分隔符
            separator = format.substring(4, 5);
        }
        String patternStr = null;
        if (separator == null)
            patternStr = "\\d{4}\\d{1,2}\\d{1,2}";
        else
            patternStr = "\\d{4}" + separator + "\\d{1,2}" + separator + "\\d{1,2}";
        
        Pattern p = Pattern.compile(patternStr);//"\\d{4}-\\d{1,2}-\\d{1,2}");        
        Matcher m = p.matcher(dateString);   
        if (!m.matches()) {   
            return false;   
        } //得到年月日 
        
        int year,month,day;
        if (separator != null){
            String[] array = dateString.split("-");   
            year = Integer.valueOf(array[0]);         
            month = Integer.valueOf(array[1]);   
            day = Integer.valueOf(array[2]);   
        }else{
            year = Integer.valueOf(dateString.substring(0, 4));
            month = Integer.valueOf(dateString.substring(4, 6));
            day = Integer.valueOf(dateString.substring(6, 8));
        }
        if (month < 1 || month > 12) {   
            return false;   
        }   
        int[] monthLengths = new int[] { 0, 31, -1, 31, 30, 31, 30, 31, 31, 30,   
                31, 30, 31 };   
        if (isLeapYear(year)) {   
            monthLengths[2] = 29;   
        } else {   
            monthLengths[2] = 28;   
        }   
        int monthLength = monthLengths[month];   
        if (day < 1 || day > monthLength) {   
            return false;   
        }   
        return true;   
    }   

    /** 是否是闰年 */  
    public static boolean isLeapYear(int year) {   
        return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0);   
    } 

    /**
     * java中对日期的加减操作 
     * gc.add(1,-1)表示年份减一. 
     * gc.add(2,-1)表示月份减一. 
     * gc.add(3.-1)表示周减一. 
     * gc.add(5,-1)表示天减一. 
     * GregorianCalendar类的add(int field,int amount)方法表示年月日加减. 
     * 当前日期前进后退几个月
     * @param date 参数表示年,月.日
     * @param num 参数表示要加减的数量
     * @param format 返回日期格式
     * @return
     */
    public String getMonth(Date date, int num, String format){
        GregorianCalendar gc =new GregorianCalendar();  
        SimpleDateFormat sf  =new SimpleDateFormat(format);
        gc.setTime(date);       
        gc.add(2,+ num);
        gc.set(gc.get(Calendar.YEAR),gc.get(Calendar.MONTH),gc.get(Calendar.DATE));             
        return sf.format(gc.getTime());     
    }
    
    /**
     * Get the date y year late then date
     * @param date
     * @param years
     * @return
     */
    public static Date getDateAfterYear(Date date,int y){
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.YEAR, y);
        return c.getTime();
    }

    /**
     * Get the date d days late then date
     * @param date
     * @param years
     * @return
     */
    public static Date getDateAfterDay(Date date,int d){
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.DATE, d);
        return c.getTime();
    }

    /**
     * This method returns the current date in the format: MM/dd/yyyy
     * 
     * @return the current date
     * @throws ParseException when String doesn't match the expected format
     */
    public static Calendar getToday() throws ParseException {
        Date today = new Date();
        SimpleDateFormat df = new SimpleDateFormat(getDatePattern());

        // This seems like quite a hack (date -> string -> date),
        // but it works ;-)
        String todayAsString = df.format(today);
        Calendar cal = new GregorianCalendar();
        cal.setTime(convertStringToDate(todayAsString));

        return cal;
    }

    public static void main(String[] args) {
        System.out.print(DateUtil.formatDateToString(DateUtil.getFirstDateOnMonth(), "yyyy-MM-dd"));
    }
}
